import { createStore } from 'vuex'
import ins from "../utils/Axios";
import { ElMessage } from "element-plus";
export default createStore({
  state: {
    //主题状态
    themeState: "",
  },
  mutations: {
    changeThemeState(state: any, val: any) {
      state.themeState = val;
    },

  },
  actions: {
    changeThemeState(context: any, val: any) {
      context.commit('changeThemeState', val);
    }
  },
  modules: {
    // 登录模块
    login: {
      state: () => ({
        loginMainState: 0,
        //是否登录
        isLoginState: 0,
        //登录用户基本信息
        userInfo: null,
      }),
      mutations: {
        isLoginState(state: any, val: any) {
          state.isLoginState = val;
        },
        userInfoChange(state: any, val: any) {
          state.userInfo = val;
        }
      },
      // 可以异步的mut
      actions: {
        isLoginState(context: any, val: any) {
          context.commit('isLoginState', val);
        },
        userInfoChange(context: any, val: any) {
          if (localStorage.getItem("token")) {
            ins.get("/user/getUserInfo").then((res: any) => {
              if (res.data.flag) {
                context.commit('isLoginState', 1);
                context.commit('userInfoChange', res.data.data);
              } else {
                localStorage.removeItem("token");
                localStorage.removeItem("userID");
                ElMessage.error("请重新登录！");
              }
            }).catch((err: any) => {
              ElMessage.error("网络超时，请刷新后重试！");
            })
          }
        }
      }
    }
  }
})
